﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace Gfw.Repository
{
    public static class RepositoryFactory
    {
        private static ISessionFactory _sessionFactory;
        private static string _config = null;

        static RepositoryFactory()
        {
            _config = AppDomain.CurrentDomain.BaseDirectory + "Config\\MySql.cfg.config";
        }

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null || _sessionFactory.IsClosed)
                {
                    Configuration cfg = new Configuration().Configure(_config);

                    cfg.Properties["connection.connection_string"] =
                       EncryptAlgorithmHelper.Decrypt2(cfg.Properties["connection.connection_string"]);

                    //cfg.Properties["connection.connection_string"] =
                    //    EncryptAlgorithmHelper.Decrypt2(cfg.Properties["connection.connection_string"], "L0ngP@ssW2rd!2012a;");



                    cfg.AddAssembly("Gfw.Models.MySql");
                    _sessionFactory = cfg.BuildSessionFactory();

                }
                return _sessionFactory;
            }
        }

        public static void Initilize(string config)
        {
            _config = config;
        }

        public static ISession OpenSession()
        {
            //HttpContext curContext = HttpContext.Current;
            //if (curContext.Items["__NhibernateSession__"] == null)
            //{
                ISession s = SessionFactory.OpenSession();
              //  curContext.Items["__NhibernateSession__"] = s;
                return s;
            //}
            //else
            //{
            //    return curContext.Items["__NhibernateSession__"] as ISession;
            //}
        }
    }
}
